#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
网球机器人通知服务模块
提供系统事件的邮件通知功能
"""

import socket
import subprocess
import threading
from datetime import datetime
from typing import Optional
from notice.notifier import send_email


class NotificationService:
    """通知服务类"""
    
    def __init__(self):
        """初始化通知服务"""
        self.enabled = True
        
    def _get_local_ip(self) -> str:
        """获取本机内网IP地址"""
        try:
            # 创建一个UDP socket连接到外部地址来获取本机IP
            with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
                s.connect(("8.8.8.8", 80))
                return s.getsockname()[0]
        except Exception:
            return "无法获取IP"
    
    def _check_git_status(self) -> dict:
        """检查Git版本状态"""
        try:
            # 获取当前分支
            current_branch = subprocess.check_output(
                ['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
                cwd='/home/ubuntu/project/tennis_robot',
                text=True
            ).strip()
            
            # 获取本地最新提交
            local_commit = subprocess.check_output(
                ['git', 'rev-parse', 'HEAD'],
                cwd='/home/ubuntu/project/tennis_robot',
                text=True
            ).strip()
            
            # 尝试获取远程最新提交
            try:
                subprocess.check_output(
                    ['git', 'fetch', 'origin', current_branch],
                    cwd='/home/ubuntu/project/tennis_robot',
                    stderr=subprocess.DEVNULL
                )
                
                remote_commit = subprocess.check_output(
                    ['git', 'rev-parse', f'origin/{current_branch}'],
                    cwd='/home/ubuntu/project/tennis_robot',
                    text=True
                ).strip()
                
                is_latest = local_commit == remote_commit
                
                return {
                    'branch': current_branch,
                    'local_commit': local_commit[:8],
                    'remote_commit': remote_commit[:8],
                    'is_latest': is_latest,
                    'status': 'success'
                }
            except subprocess.CalledProcessError:
                return {
                    'branch': current_branch,
                    'local_commit': local_commit[:8],
                    'remote_commit': '无法获取',
                    'is_latest': None,
                    'status': 'fetch_failed'
                }
                
        except Exception as e:
            return {
                'branch': '未知',
                'local_commit': '未知',
                'remote_commit': '未知',
                'is_latest': None,
                'status': 'error',
                'error': str(e)
            }
    
    def send_startup_notification(self):
        """发送系统启动通知"""
        if not self.enabled:
            return
            
        def _send_async():
            try:
                current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                local_ip = self._get_local_ip()
                git_status = self._check_git_status()
                
                subject = "网球机器人系统启动通知"
                
                body = f"""网球机器人系统已启动

启动时间: {current_time}
内网IP地址: {local_ip}

Git版本信息:
- 当前分支: {git_status['branch']}
- 本地提交: {git_status['local_commit']}
- 远程提交: {git_status['remote_commit']}
"""
                
                if git_status['status'] == 'success':
                    if git_status['is_latest']:
                        body += "- 版本状态: 已是最新版本"
                    else:
                        body += "- 版本状态: 发现新版本，建议手动更新"
                elif git_status['status'] == 'fetch_failed':
                    body += "- 版本状态: 无法连接远程仓库，请检查网络"
                else:
                    body += f"- 版本状态: 检查失败 ({git_status.get('error', '未知错误')})"
                
                body += f"""

Web控制界面: http://{local_ip}:5000

系统已准备就绪，可以开始使用。
"""
                
                success = send_email(subject, body)
                if success:
                    print("启动通知发送成功")
                else:
                    print("启动通知发送失败")
                    
            except Exception as e:
                print(f"发送启动通知时出错: {e}")
        
        # 在后台线程中发送通知，避免阻塞主程序
        threading.Thread(target=_send_async, daemon=True).start()
    
    def send_pickup_start_notification(self):
        """发送开始拾取通知"""
        if not self.enabled:
            return
            
        def _send_async():
            try:
                current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                local_ip = self._get_local_ip()
                
                subject = "网球机器人开始拾取作业"
                
                body = f"""网球机器人已开始拾取作业

开始时间: {current_time}
设备IP: {local_ip}

机器人正在执行网球拾取任务，您可以通过以下方式监控:
- Web界面: http://{local_ip}:5000
- 实时视频流查看拾取进度
- 系统状态监控

如需紧急停止，请使用Web界面的紧急停止功能。
"""
                
                success = send_email(subject, body)
                if success:
                    print("拾取开始通知发送成功")
                else:
                    print("拾取开始通知发送失败")
                    
            except Exception as e:
                print(f"发送拾取开始通知时出错: {e}")
        
        # 在后台线程中发送通知，避免阻塞主程序
        threading.Thread(target=_send_async, daemon=True).start()
    
    def enable_notifications(self):
        """启用通知"""
        self.enabled = True
        print("通知服务已启用")
    
    def disable_notifications(self):
        """禁用通知"""
        self.enabled = False
        print("通知服务已禁用")
    
    def is_enabled(self) -> bool:
        """检查通知服务是否启用"""
        return self.enabled


# 创建全局通知服务实例
notification_service = NotificationService()
